package com.example.bingobox.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bingobox.R;
import com.example.bingobox.adapter.TravelCityAdapter;
import com.example.bingobox.model.State;
import com.example.bingobox.model.State.Location;
import com.example.bingobox.utils.LocationUtils;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class CityManageDialog extends DialogFragment implements TravelCityAdapter.OnCityRemoveListener {
    private State state;
    private OnCityUpdateListener listener;
    private TextView homeCityText;
    private TextView nativeCityText;
    private TravelCityAdapter adapter;

    public static CityManageDialog newInstance(State state) {
        CityManageDialog dialog = new CityManageDialog();
        dialog.state = state;
        return dialog;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_city_manage, null);

        initializeViews(view);
        setupListeners(view);
        updateCityDisplay();

        return builder.setView(view)
                .setTitle("城市类型管理")
                .setPositiveButton("关闭", null)
                .create();
    }

    private void initializeViews(View view) {
        homeCityText = view.findViewById(R.id.home_city);
        nativeCityText = view.findViewById(R.id.native_city);
        RecyclerView travelCitiesList = view.findViewById(R.id.travel_cities);

        adapter = new TravelCityAdapter(state.getTravelCities(), this);
        travelCitiesList.setLayoutManager(new LinearLayoutManager(getContext()));
        travelCitiesList.setAdapter(adapter);
    }

    private void setupListeners(View view) {
        view.findViewById(R.id.btn_set_home).setOnClickListener(v -> {
            LocationUtils.getCurrentLocation(requireContext(), new LocationUtils.LocationCallback() {
                @Override
                public void onLocationReceived(State.Location location) {
                    Geocoder geocoder = new Geocoder(requireContext(), Locale.getDefault());
                    try {
                        List<Address> addresses = geocoder.getFromLocation(
                            location.getLatitude(),
                            location.getLongitude(),
                            1
                        );
                        
                        if (addresses != null && !addresses.isEmpty()) {
                            Address address = addresses.get(0);
                            State.Location homeCity = new State.Location(
                                address.getLocality(),
                                location.getLatitude(),
                                location.getLongitude()
                            );
                            state.setHomeCity(homeCity);
                            state.updateState();
                            updateCityDisplay();
                            notifyUpdate();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(getContext(), "获取城市信息失败: " + e.getMessage(), 
                            Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onLocationFailed(String error) {
                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                }
            });
        });

        view.findViewById(R.id.btn_set_native).setOnClickListener(v -> {
            LocationUtils.getCurrentLocation(requireContext(), new LocationUtils.LocationCallback() {
                @Override
                public void onLocationReceived(State.Location location) {
                    Geocoder geocoder = new Geocoder(requireContext(), Locale.getDefault());
                    try {
                        List<Address> addresses = geocoder.getFromLocation(
                            location.getLatitude(),
                            location.getLongitude(),
                            1
                        );
                        
                        if (addresses != null && !addresses.isEmpty()) {
                            Address address = addresses.get(0);
                            State.Location nativeCity = new State.Location(
                                address.getLocality(),
                                location.getLatitude(),
                                location.getLongitude()
                            );
                            state.setNativeCity(nativeCity);
                            state.updateState();
                            updateCityDisplay();
                            notifyUpdate();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(getContext(), "获取城市信息失败: " + e.getMessage(), 
                            Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onLocationFailed(String error) {
                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                }
            });
        });

        view.findViewById(R.id.btn_add_travel).setOnClickListener(v -> {
            LocationUtils.getCurrentLocation(requireContext(), new LocationUtils.LocationCallback() {
                @Override
                public void onLocationReceived(State.Location location) {
                    state.addTravelCity(location);
                    adapter.notifyDataSetChanged();
                    notifyUpdate();
                }

                @Override
                public void onLocationFailed(String error) {
                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                }
            });
        });

        view.findViewById(R.id.btn_search_city).setOnClickListener(v -> {
            CitySearchDialog searchDialog = new CitySearchDialog();
            searchDialog.setOnCitySelectedListener(location -> {
                state.addTravelCity(location);
                adapter.notifyDataSetChanged();
                notifyUpdate();
            });
            searchDialog.show(getChildFragmentManager(), "city_search");
        });
    }

    private void updateCityDisplay() {
        Location homeCity = state.getHomeCity();
        Location nativeCity = state.getNativeCity();

        homeCityText.setText(homeCity != null ? homeCity.getName() : "未设置");
        nativeCityText.setText(nativeCity != null ? nativeCity.getName() : "未设置");
    }

    @Override
    public void onCityRemove(Location city) {
        state.removeTravelCity(city);
        adapter.notifyDataSetChanged();
        notifyUpdate();
    }

    private void notifyUpdate() {
        if (listener != null) {
            listener.onCityUpdated();
        }
    }

    public interface OnCityUpdateListener {
        void onCityUpdated();
    }

    public void setOnCityUpdateListener(OnCityUpdateListener listener) {
        this.listener = listener;
    }
} 